package com.app.webaiproject.util;

import android.os.AsyncTask;
import android.util.Log;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.app.webaiproject.BaseActivity.MainActivity;

public class HttpData extends AsyncTask<String, Void, String> {
    // 请替换为真实的 API 密钥
    private static final String API_KEY = "sk-55f54cb4e2b348ebaa890db1d6380515";
    private static final String APP_ID = "1f411c3c08f54ff2a5c64865383b5aba";
    private final MainActivity.HttpPostDataListener listener;

    public HttpData(MainActivity.HttpPostDataListener listener) {
        this.listener = listener;
    }

    @Override
    protected String doInBackground(String... strings) {
        if (strings.length == 0) return "请输入内容";
        String userInput = strings[0];

        try {
            ApplicationParam param = ApplicationParam.builder()
                    .apiKey(API_KEY)
                    .appId(APP_ID)
                    .prompt(userInput)
                    .hasThoughts(true) // 是否返回思考过程
                    .build();

            Application application = new Application();
            com.alibaba.dashscope.app.ApplicationResult result = application.call(param);

            Log.d("AI_Response", "思考过程：" + result.getOutput().getThoughts());
            return result.getOutput().getText();

        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            Log.e("AI_Error", "API 调用失败：" + e.getMessage());
            return "抱歉，AI 服务出错：" + e.getMessage();
        } catch (Exception e) {
            Log.e("AI_Error", "未知错误：" + e.getMessage());
            return "抱歉，发生未知错误";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (listener != null) {
            listener.getDateUrl(result); // 通过接口回调结果
        }
    }
}